package shopCart

import (
	"context"
	"go_final/mxshop_api/order_web/api"
	"go_final/mxshop_api/order_web/forms"
	"go_final/mxshop_api/order_web/global"
	goodspb "go_final/mxshop_api/order_web/proto/protofile/goods"
	inventorypb "go_final/mxshop_api/order_web/proto/protofile/inventory"
	orderpb "go_final/mxshop_api/order_web/proto/protofile/order"
	"net/http"
	"strconv"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	userID, _ := c.Get("userId")

	res, err := global.OrderClient.CartItemList(context.Background(), &orderpb.UserInfo{
		UserID: int32(userID.(uint)),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	ids := make([]int32, 0)
	for _, item := range res.Data {
		ids = append(ids, item.GoodsID)
	}

	if len(ids) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"total": 0,
		})
		return
	}
	// 请求商品服务获取商品信息
	goodsRes, err := global.GoodsClient.BatchGetGoods(context.Background(), &goodspb.BatchGoodsIdInfo{
		Id: ids,
	})

	rsp := gin.H{
		"total": res.Total,
		"data":  goodsRes.Data,
	}

	c.JSON(http.StatusOK, rsp)
}

func Delete(c *gin.Context) {
	userID, _ := c.Get("userId")
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	res, err := global.OrderClient.DeleteCartItem(context.Background(), &orderpb.CartItemRequest{
		GoodsID: int32(goodsIDInt),
		UserID:  int32(userID.(uint)),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func New(c *gin.Context) {
	shopCartForm := forms.ShopCartItemForm{}
	err := c.ShouldBind(&shopCartForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	// 记得查一下商品是否存在
	_, err = global.GoodsClient.GetGoodsDetail(context.Background(), &goodspb.GoodInfoRequest{
		Id: int32(shopCartForm.GoodsID),
	})
	if err != nil {
		zap.S().Error("[List] 查询 【商品信息】 失败")
		api.HandleGrpcError2Http(err, c)
		return
	}

	// 查库存是否足够
	invInfo, err := global.InvClient.InventoryDetail(context.Background(), &inventorypb.GoodsInvInfo{
		GoodsID: int32(shopCartForm.GoodsID),
	})
	if err != nil {
		zap.S().Error("[List] 查询 【库存信息】 失败")
		api.HandleGrpcError2Http(err, c)
		return
	}
	if invInfo.Num < int32(shopCartForm.Num) {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "库存不足",
		})
		return
	}

	userID, _ := c.Get("userId")
	res, err := global.OrderClient.CreateCartItem(context.Background(), &orderpb.CartItemRequest{
		UserID:  int32(userID.(uint)),
		GoodsID: int32(shopCartForm.GoodsID),
		Num:     int32(shopCartForm.Num),
		Checked: true,
	})

	if err != nil {
		zap.S().Error("【添加到购物车】 失败")
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Update(c *gin.Context) {
	shopCartForm := forms.ShopCartItemUpdateForm{}
	if err := c.ShouldBind(&shopCartForm); err != nil {
		api.HandleValidateError(c, err)
		return
	}

	userID, _ := c.Get("userId")
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	request := orderpb.CartItemRequest{
		UserID:  int32(userID.(uint)),
		GoodsID: int32(goodsIDInt),
		Num:     int32(shopCartForm.Num),
	}

	if shopCartForm.Checked != nil {
		request.Checked = *shopCartForm.Checked
	}

	res, err := global.OrderClient.UpdateCartItem(context.Background(), &request)
	if err != nil {
		zap.S().Errorw("【更新到购物车】 失败")
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}
